package com.tj.collection.task;

import com.alibaba.fastjson.JSONObject;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.DateUtil;
import com.fqgj.common.utils.StringUtils;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.kly.user.chatterService.ChatterUserService;
import com.kly.user.dto.chatter.response.UserChatterModeDto;
import com.tj.collection.db.dao.CusomExtDao;
import com.tj.collection.db.dao.RptCustomQuerySqlDao;
import com.tj.collection.db.dao.RptModelDataPreDayDao;
import com.tj.collection.db.dao.RptModelLikeDao;
import com.tj.collection.db.entity.RptCustomQuerySqlEntity;
import com.tj.collection.db.entity.RptModelDataPreDayEntity;
import com.tj.collection.db.entity.RptModelLikeEntity;
import com.tj.collection.enums.DataReportTypeEnum;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * model每日数据统计
 */
@Service
public class ModelDataTask {

    private static Log logger = LogFactory.getLog(ModelDataTask.class);
    @Resource
    RptCustomQuerySqlDao customQuerySqlDao;
    @Resource
    RptModelDataPreDayDao modelDataPreDayDao;
    @Resource
    ChatterUserService chatterUserService;
    @Resource
    CusomExtDao cusomExtDao;

    /**
     * 统计频率：3600s
     */
    @Scheduled(fixedDelay = 1000 * 3600)
    public void run() {
        final List<UserChatterModeDto> modesByChatterAccounts = chatterUserService.getModesByChatterAccount(null);
        if (CollectionUtils.isEmpty(modesByChatterAccounts)) {
            return;
        }
        // 初始化数据表
        initModelData(modesByChatterAccounts);
        // 获取自定义sql
        final List<RptCustomQuerySqlEntity> customSqlList = getCustomSqlList();
        if (CollectionUtils.isEmpty(customSqlList)) {
            return;
        }
        for (RptCustomQuerySqlEntity customQuerySql : customSqlList) {
            logger.info("====name{}， sql:{}", customQuerySql.getName(), customQuerySql.getSqlText());
            final List<Map<String, Object>> records = cusomExtDao.customQuery2(customQuerySql.getSqlText());
            if (CollectionUtils.isEmpty(records)) {
                continue;
            }

            for (Map<String, Object> item : records) {
                final String updateSql = buildUpdateSql(customQuerySql, item);
                if (StringUtils.isEmpty(updateSql)) {
                    continue;
                }
                modelDataPreDayDao.updateModelData(updateSql);
                // 只执行一次
                if (customQuerySql.getExecuteOnceFlag() == 1) {
                    break;
                }
            }
        }
    }

    @Resource
    RptModelLikeDao modelLikeDao;

    /**
     * model 爆光率：每天凌晨4点执行
     */
    @Scheduled(cron = "0 0 4 * * ?")
    public void modelLike() {

        // 获取自定义sql
        final List<RptCustomQuerySqlEntity> customSqlList =  customQuerySqlDao.listRptCustomQuerySqlByType(DataReportTypeEnum.MODEL_LIKE.getType());
        if (CollectionUtils.isEmpty(customSqlList)) {
            return;
        }

        final RptCustomQuerySqlEntity customQuerySql = customSqlList.get(0);

        final List<Map<String, Object>> records = cusomExtDao.customQuery2(customQuerySql.getSqlText());
        if (CollectionUtils.isEmpty(records)) {
            return;
        }

        final Map<String, RptModelLikeEntity> allData = modelLikeDao.listAllModelData();

        for (Map<String, Object> item : records) {
            if (item.containsKey("model_user_code")) {
                String modelUserCode = item.get("model_user_code").toString();
                final boolean isExists = allData.containsKey(modelUserCode);
                if (isExists) {
                    final RptModelLikeEntity existsRecord = allData.get(modelUserCode);
                    existsRecord.setLikeNum(Integer.parseInt(item.get("like_num").toString()));
                    existsRecord.setDislikeNum(Integer.parseInt(item.get("dislike_num").toString()));
                    existsRecord.setPassNum(Integer.parseInt(item.get("pass_num").toString()));
                    existsRecord.setTotalNum(Integer.parseInt(item.get("total_num").toString()));
                    modelLikeDao.updateByPrimaryKey(existsRecord);
                } else {
                    RptModelLikeEntity newRecord = new RptModelLikeEntity();
                    newRecord.setModelUserCode(modelUserCode);
                    newRecord.setLikeNum(Integer.parseInt(item.get("like_num").toString()));
                    newRecord.setDislikeNum(Integer.parseInt(item.get("dislike_num").toString()));
                    newRecord.setPassNum(Integer.parseInt(item.get("pass_num").toString()));
                    newRecord.setTotalNum(Integer.parseInt(item.get("total_num").toString()));
                    modelLikeDao.insert(newRecord);
                }
            }
        }
    }


    /**
     * 封装更新语句
     */
    private String buildUpdateSql(RptCustomQuerySqlEntity customQuerySql, Map<String, Object> item) {
        if (CollectionUtils.isEmpty(item)) {
            return null;
        }
        String updateSqlStr = customQuerySql.getUpdateSqlText();
        final JSONObject updateSqlJson = JSONObject.parseObject(updateSqlStr);
        String updateSql = updateSqlJson.getString("updateSql");
        final String updateColumns = updateSqlJson.getString("updateColumn");
        try {

            if (StringUtils.isNotEmpty(updateColumns)) {
                final List<String> columns = Splitter.on(',').splitToList(updateColumns);
                for (String column : columns) {
                    updateSql = updateSql.replace("##" + column + "##", item.get(column) == null ? "0" : item.get(column).toString() );
                }
            }
            final String condition = updateSqlJson.getString("condition");
            if (StringUtils.isNotEmpty(condition)) {
                final List<String> conditionColumns = Splitter.on(',').splitToList(condition);
                for (String conditionColumn : conditionColumns) {
                    updateSql = updateSql.replace("##" + conditionColumn + "##", item.get(conditionColumn).toString());
                }
            }
            logger.info("buildUpdateSql:{}", updateSql);
            return updateSql;
        } catch (Exception e) {
            logger.error("buildSqlError:{}, customQuerySql:{}", updateSql, JSONObject.toJSONString(customQuerySql), e);
        }
        return null;
    }


    private List<RptCustomQuerySqlEntity> getCustomSqlList() {
        return customQuerySqlDao.listRptCustomQuerySqlByType(DataReportTypeEnum.MODEL_DATA.getType());
    }

    private void initModelData(List<UserChatterModeDto> modesByChatterAccounts) {
        // 删除当天数据
        modelDataPreDayDao.removeTodayData();
        // 初始化数据
        List<RptModelDataPreDayEntity> modelDataList = Lists.newArrayList();
        for (UserChatterModeDto model : modesByChatterAccounts) {
            RptModelDataPreDayEntity modelData = new RptModelDataPreDayEntity();
            modelData.setChatterAccount(model.getChatterAccount());
            modelData.setChatterUserCode(model.getChatterUserCode());
            modelData.setChatterName(model.getChatterNickName());
            modelData.setModelUserCode(model.getModelUserCode());
            modelData.setModelName(model.getModelNickName());
            modelData.setCreateDt(Integer.parseInt(DateUtil.getDate("yyyyMMdd")));
            modelDataList.add(modelData);
        }
        // 批量插入当天model数据
        modelDataPreDayDao.batchInsertData(modelDataList);

    }

}
